#region Terms of Usage
/*
 * Copyright 2006 Sameera Perera
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;

namespace needle.Services.soab.Connectivity
{
    public class ConnectionManager
    {
        private Timer timer;
        private IConnectionDetectionStrategy detectionStrategy;

        /// <summary>Occurs when the connection state changes.</summary>
        public event ConnectionStateChangedEventHandler ConnectionStateChanged;
        /// <summary>Occurs after the <see cref="ConnectionManager"/> performs its
        /// periodic connection-state check.</summary>
        /// <remarks>Use this event when some action needs to be synchronized with
        /// the querying of the connection state.</remarks>
        public event EventHandler QueriedConnectionState;

        public IConnectionDetectionStrategy ConnectionDetectionStrategy
        {
            get { return detectionStrategy; }
            set
            {
                detectionStrategy = value;
                detectionStrategy.ConnectionStateChanged += new ConnectionStateChangedEventHandler( detectionStrategy_ConnectionStateChanged );
                detectionStrategy.GetConnectionStatus();
            }
        }

        // Re-fire the ConnectionStateChanged even fired in the detection strategy, so that
        // clients may catch it through the ConnectionManager.
        void  detectionStrategy_ConnectionStateChanged(object sender, ConnectionStateChangedEventArgs e)
        {
            if ( this.ConnectionStateChanged != null )
                this.ConnectionStateChanged( this, e );
        } 

        public bool IsConnected { get{ return detectionStrategy.IsConnected; } }

        public ConnectionState ConnectionState
        {
            get { return detectionStrategy.ConnectionState; }
        }

        #region Singleton Implementation

        private static ConnectionManager instance;

        public static ConnectionManager Instance
        {
            get
            {
                lock ( typeof( ConnectionManager ) )
                {
                    if ( instance == null )
                        instance = new ConnectionManager();
                }
                return instance;
            }
        }

        private ConnectionManager()
        {
            // By default use the WinInet Strategy
            this.detectionStrategy  = new WinInetConnectionDetectionStartegy();
            this.timer              = new Timer();

            timer.Interval  = 2000;
            timer.Elapsed   += new ElapsedEventHandler( timer_Elapsed );
            timer.Start();
        }
        #endregion

        //private bool GetConnectionStatus ()
        //{
        //    int cnxDesc = 0;
        //    bool retVal = InternetGetConnectedState( out cnxDesc, 0 );


        //    if ( 
        //        ( this.ConnectionStateChanged != null )
        //        &&
        //        ( ( retVal && currentState != ConnectionState.Online ) ||
        //             ( !retVal && currentState != ConnectionState.Offline )
        //        )
        //    )
        //    {
        //        ConnectionState newState   = retVal ? ConnectionState.Online : ConnectionState.Offline;
        //        ConnectionState oldState   = currentState;
        //        currentState = newState;

        //        this.ConnectionStateChanged( this, new ConnectionStateChangedEventArgs( oldState, newState ) );
        //    }
        //    return retVal;
        //}

        [System.Diagnostics.DebuggerStepThrough]
        void timer_Elapsed( object sender, ElapsedEventArgs e )
        {
            detectionStrategy.GetConnectionStatus();
            if ( this.QueriedConnectionState != null )
                this.QueriedConnectionState( this, EventArgs.Empty );
        }
    }
}
